﻿using MacroRecorder.Macro;
using MacroRecorder.Macro.EventParam;
using MacroRecorder.Macro.Events;
using MacroRecorder.Macro.Structs;
using MacroRecorder.Properties;
using SharpFind;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MacroRecorder.Forms
{
    /// <summary>
    /// Made By BahNahNah
    /// uid=2388291
    /// </summary>
    public partial class MainWindow : Form
    {
        private const string FILEPATH = "Config.json";
        private const string PASSSTRING = "ALL PASS";
        private MRecorder Recorder = new MRecorder(false);
        /// <summary>
        /// 当前鼠标事件列表
        /// </summary>
        private List<IMacroEvent> CurrentMacro = new List<IMacroEvent>();
        private List<IMacroEvent> ResultEvents = new List<IMacroEvent>();
        /// <summary>
        /// 选中事件集合
        /// </summary>
        private List<ListViewItem> SelectedItems = new List<ListViewItem>();
        /// <summary>
        /// 事件索引
        /// </summary>
        private int index;
        /// <summary>
        /// 编辑标记，0-主流程，1-次流程
        /// </summary>
        private int _editFlag;
        private ParamServer Param;
        private Frm_Main fm;
        private formMacroNotify mn;
        private formMacroPlaying mp;
        public MainWindow()
        {
            InitializeComponent();
            Recorder.OnEvent += Recorder_OnEvent;
        }

        private void ClearCurrent()
        {
            if (_editFlag == 0)
            {
                CurrentMacro.Clear();
                lvEvents.Items.Clear();
            }
            else
            {
                ResultEvents.Clear();
                listView1.Items.Clear();
            }
            index = 0;
        }

        private void Recorder_OnEvent(IMacroEvent mEvent)
        {
            AddEvent(mEvent, _editFlag);
        }

        private void AddEvent(IMacroEvent mEvent, int flag)
        {
            ListViewItem i = new ListViewItem(mEvent.GetEventType());
            i.SubItems.Add(mEvent.GetEventString());
            mEvent.EventIndex = index++;
            i.SubItems.Add((mEvent.EventIndex).ToString());
            i.ImageKey = mEvent.GetEventType();
            i.Tag = mEvent;
            if (flag == 0)
            {
                lvEvents.Items.Add(i);
                CurrentMacro.Add(mEvent);
            }
            else
            {
                listView1.Items.Add(i);
                ResultEvents.Add(mEvent);
            }
        }
        private void MainWindow_Load(object sender, EventArgs e)
        {
            ImageList il = new ImageList();
            il.Images.Add("Mouse", Resources.mouse);
            il.Images.Add("Keyboard", Resources.keyboard);
            il.Images.Add("Delay", Resources.time);
            il.Images.Add("InputBarCode", Resources.barcode_32px);
            lvEvents.SmallImageList = il;
            listView1.SmallImageList = il;
            ShowParam();
        }
        private void ShowParam()
        {
            try
            {
                Param = SerializableHelper.Read<ParamServer>(FILEPATH);
                var events = AnalysisParam(Param.FirstParam);
                _editFlag = 0;
                ClearCurrent();
                foreach (IMacroEvent lEvent in events)
                    AddEvent(lEvent, _editFlag);
                var events2 = AnalysisParam(Param.SecondParam);
                _editFlag = 1;
                ClearCurrent();
                foreach (IMacroEvent lEvent in events2)
                    AddEvent(lEvent, _editFlag);
                ModelTx.Text = Param.ModelName;
                TimeoutTx.Text = Param.TimeOut.ToString();
                ClassTextTx.Text = Param.ClassName;
                TitleTextTx.Text = Param.TitleName;
                ColorXLabel.Text = Param.ColorX.ToString();
                ColorYLabel.Text = Param.ColorY.ToString();
                dataGridView1.Rows.Clear();
                foreach (var s in Param.RuningTexts)
                {
                    int index = dataGridView1.Rows.Add();
                    dataGridView1.Rows[index].Cells[0].Value = s;
                }
                var type = (int)Param.ExtractType;
                if (type == 0)
                    TextRbtn.Checked = true;
                if (type == 1)
                    ColorRbtn.Checked = true;
                if (type == 2)
                    BothRbtn.Checked = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载参数异常{ex.Message }");
            }
        }
        private void SaveParam()
        {
            var param = new ParamServer();
            try
            {
                param.FirstParam = ExtractParam(CurrentMacro);
                param.SecondParam = ExtractParam(ResultEvents);
                param.ModelName = ModelTx.Text;
                param.TimeOut = int.Parse(TimeoutTx.Text);
                param.ClassName = ClassTextTx.Text;
                param.TitleName = TitleTextTx.Text;
                //坐标
                param.ColorX = int.Parse(ColorXLabel.Text);
                param.ColorY = int.Parse(ColorYLabel.Text);
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    if (row.Cells[0].Value != null)
                        param.RuningTexts.Add(row.Cells[0].Value.ToString());
                }
                if (TextRbtn.Checked)
                    param.ExtractType = ExtractEnum.Text;
                if (ColorRbtn.Checked)
                    param.ExtractType = ExtractEnum.Color;
                if (BothRbtn.Checked)
                    param.ExtractType = ExtractEnum.Both;
                SerializableHelper.Save(param, FILEPATH);
                Param = param;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存参数异常,{ex.Message}");
            }
        }
        private void recordANewMacroToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (formNewMacro newMacro = new formNewMacro())
            {
                if (newMacro.ShowDialog() != DialogResult.OK)
                    return;

                Recorder.MouseMovementCaptureDelay = newMacro.MouseMovementCaptureDelay;
                Recorder.CaptureMouseMovements = newMacro.CaptureMouseMovements;

                using (formMacroNotify mn = new formMacroNotify(Recorder, newMacro.RecordKeyboard, newMacro.RecordMouse, newMacro.DelayBeforeRecord))
                {
                    _editFlag = 0;
                    ClearCurrent();
                    this.Hide();
                    mn.ShowDialog();
                    this.Show();
                }
            }
        }

        private void playMacroToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (CurrentMacro.Count < 1)
                return;
            Clipboard.SetDataObject(BarcodeTx.Text);
            using (formMacroPlaying mp = new formMacroPlaying(CurrentMacro.ToArray()))
            {
                this.Hide();
                mp.ShowDialog();
                this.Show();
            }
        }

        private void removeSelectedEventToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lvEvents.SelectedItems.Count > 0)
            {
                foreach (ListViewItem i in lvEvents.SelectedItems)
                {
                    // ListViewItem i = lvEvents.SelectedItems[0];
                    IMacroEvent mEvent = (IMacroEvent)i.Tag;
                    CurrentMacro.Remove(mEvent);
                    Recorder.Remove(mEvent);
                    lvEvents.Items.Remove(i);
                }
            }
        }
        private MacroEventParam ExtractParam(List<IMacroEvent> events)
        {
            var param = new MacroEventParam();
            foreach (IMacroEvent e in events)
            {
                var item = e.GetParam();
                var etype = (MacroEventType)item.EnumType;
                switch (etype)
                {
                    case MacroEventType.Delay:
                        param.Delays.Add((DelayParam)item);
                        break;
                    case MacroEventType.Keyboard:
                        param.Keyboards.Add((KeyBoardParam)item);
                        break;
                    case MacroEventType.Mouse:
                        param.Mouses.Add((MouseParam)item);
                        break;
                    case MacroEventType.InputBarCode:
                        param.InputBars.Add((InputBarcodeParam)item);
                        break;
                }
            }
            return param;
        }
        private List<IMacroEvent> AnalysisParam(MacroEventParam param)
        {
            List<IMacroEvent> events = new List<IMacroEvent>();
            //var param = SerializableHelper.Read<MacroEventParam>(FILEPATH);
            foreach (var e in param.InputBars)
            {
                var ievet = new MacroEvent_InputBarcode();
                ievet.SetParam(e);
                events.Add(ievet);
            }
            foreach (var e in param.Delays)
            {
                var ievet = new MacroEvent_Delay(e.DelayMS);
                ievet.SetParam(e);
                events.Add(ievet);
            }
            foreach (var e in param.Keyboards)
            {
                KeyboardEvent eventData = new KeyboardEvent();
                eventData.vKeyCode = e.VKeyCode;
                eventData.scanCode = e.ScanCode;
                eventData.Flags = e.Flags;
                eventData.Time = 0;
                eventData.dwExtraInfo = WinApi.GetMessageExtraInfo();
                var ievet = new MacroEvent_Keyboard((eKeyboardEvent)e.EventType, eventData);
                ievet.SetParam(e);
                events.Add(ievet);
            }
            foreach (var e in param.Mouses)
            {
                eMouseButton mButton = (eMouseButton)e.Button;
                MouseEvent mEvent = new MouseEvent();
                mEvent.mouseData = e.MouseData;
                mEvent.Location = new mPoint();
                mEvent.Location.X = e.LocationX;
                mEvent.Location.Y = e.LocationY;
                mEvent.Flags = e.Flags;
                var ievet = new MacroEvent_Mouse(mEvent, mButton);
                ievet.SetParam(e);
                events.Add(ievet);
            }
            events.Sort((x, y) => x.EventIndex.CompareTo(y.EventIndex));
            return events;
        }

        private void saveMacroToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //ExtractParam();
        }

        private void loadAMacroToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var param = SerializableHelper.Read<ParamServer>(FILEPATH);
            var events = AnalysisParam(param.FirstParam);
            CurrentMacro.Clear();
            lvEvents.Items.Clear();
            foreach (IMacroEvent lEvent in events)
                AddEvent(lEvent, 0);
        }

        private void selectItemsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lvEvents.SelectedItems.Count > 0)
            {
                lvEvents.ContextMenuStrip = cmEdit;
                foreach (ListViewItem i in lvEvents.SelectedItems)
                {
                    i.ForeColor = Color.Red;
                    SelectedItems.Add(i);
                }
            }
        }

        private void deselectToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void allToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem i in SelectedItems)
            {
                i.ForeColor = Color.Black;
            }
            SelectedItems.Clear();
            lvEvents.ContextMenuStrip = cmMacro;
        }

        private void selectedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lvEvents.SelectedItems.Count > 0)
            {
                foreach (ListViewItem i in lvEvents.SelectedItems)
                {
                    if (SelectedItems.Contains(i))
                    {
                        i.ForeColor = Color.Black;
                        SelectedItems.Remove(i);
                    }
                }
                if (SelectedItems.Count < 1)
                {
                    lvEvents.ContextMenuStrip = cmMacro;
                }
            }
        }

        private void moveHereToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lvEvents.SelectedItems.Count > 0)
            {
                int moveIndex = lvEvents.SelectedIndices[0];
                for (int i = SelectedItems.Count - 1; i >= 0; i--)
                {
                    IMacroEvent mEvent = (IMacroEvent)SelectedItems[i].Tag;

                    lvEvents.Items.Remove(SelectedItems[i]);
                    CurrentMacro.Remove(mEvent);

                    lvEvents.Items.Insert(moveIndex, SelectedItems[i]);
                    CurrentMacro.Insert(moveIndex, mEvent);
                }
            }
        }

        private void InsertItemEventToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lvEvents.SelectedItems.Count == 1)
            {
                int moveIndex = lvEvents.SelectedIndices[0];
                IMacroEvent mEvent = (IMacroEvent)lvEvents.SelectedItems[0].Tag;
                var mIEvent = new MacroEvent_InputBarcode { EventIndex = mEvent.EventIndex };
                foreach (var ev in CurrentMacro)
                    if (ev.EventIndex >= mEvent.EventIndex)
                        ev.EventIndex++;
                CurrentMacro.Insert(moveIndex, mIEvent);
                ListViewItem i = new ListViewItem(mIEvent.GetEventType());
                i.SubItems.Add(mIEvent.GetEventString());
                i.SubItems.Add((mIEvent.EventIndex).ToString());
                i.ImageKey = mIEvent.GetEventType();
                i.Tag = mIEvent;
                lvEvents.Items.Insert(moveIndex, i);
            }
        }
        private void InsertDelayEventToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lvEvents.SelectedItems.Count == 1)
            {
                int moveIndex = lvEvents.SelectedIndices[0];
                IMacroEvent mEvent = (IMacroEvent)lvEvents.SelectedItems[0].Tag;
                var mIEvent = new MacroEvent_Delay(200) { EventIndex = mEvent.EventIndex };
                foreach (var ev in CurrentMacro)
                    if (ev.EventIndex >= mEvent.EventIndex)
                        ev.EventIndex++;
                CurrentMacro.Insert(moveIndex, mIEvent);
                ListViewItem i = new ListViewItem(mIEvent.GetEventType());
                i.SubItems.Add(mIEvent.GetEventString());
                i.SubItems.Add((mIEvent.EventIndex).ToString());
                i.ImageKey = mIEvent.GetEventType();
                i.Tag = mIEvent;
                lvEvents.Items.Insert(moveIndex, i);
            }
        }
        private void FlowStartBtn_Click(object sender, EventArgs e)
        {
            var mainIntptr = (IntPtr)(Convert.ToInt32(MainHandleTx.Text));
            if (mainIntptr == IntPtr.Zero)
            {
                return;
            }
            Stopwatch sw = new Stopwatch();
            sw.Start();
            ErrorStatusLabel.Text = $"测试开始！";
            ErrorStatusLabel.BackColor = Color.Gray;
            WinApi.SetWindowPos(mainIntptr, 0, 0, 0, 0, 0, 0x0005);
            playMacroToolStripMenuItem_Click(null, null);
            var cts = new CancellationTokenSource();
            var rtext = string.Empty;
            List<Task> tasks = new List<Task>();
            if (Param.ExtractType != ExtractEnum.Color)
                tasks.Add(Task.Factory.StartNew(() =>
                {
                    while (!cts.Token.IsCancellationRequested)
                    {
                        var text = GetResultText();
                        if (!string.IsNullOrEmpty(text) && !Param.RuningTexts.Contains(text))
                        {
                            rtext = text;
                            break;
                        }
                        Task.Delay(50).Wait();
                    }
                    sw.Stop();
                    var res = AnalysisText(rtext);
                    ResultPanel.Invoke(new Action(() => DrawTextOnPanel(ResultPanel, res)));
                    ResultLabel.Invoke(new Action(() => ResultLabel.Text = $"结果：{(res ? "OK" : "NG")}"));
                    ElapsedLabel.Invoke(new Action(() => ElapsedLabel.Text = $"耗时：{sw.ElapsedMilliseconds}ms"));
                }, cts.Token));

            if (Param.ExtractType != ExtractEnum.Text)
                tasks.Add(Task.Factory.StartNew(() =>
            {
                var res = false;
                while (!cts.Token.IsCancellationRequested)
                {
                    IntPtr hdc = WinApi.GetDC(new IntPtr(0));//取到设备场景(0就是全屏的设备场景)
                    uint c = WinApi.GetPixel(hdc, Param.ColorX, Param.ColorY);
                    int r = (int)(c & 0xFF);
                    int g = (int)(c & 0xFF00) / 256;
                    int b = (int)(c & 0xFF0000) / 65536;
                    if (GetStatusByColor(r, g, b) == RunStatusEnum.Finished)
                    {
                        res = GetResultByColor(r, g, b) == 2;
                        break;
                    }
                    Task.Delay(50).Wait();
                }
                sw.Stop();
                ResultPanel.Invoke(new Action(() => DrawTextOnPanel(ResultPanel, res)));
                ResultLabel.Invoke(new Action(() => ResultLabel.Text = $"结果：{(res ? "OK" : "NG")}"));
                ElapsedLabel.Invoke(new Action(() => ElapsedLabel.Text = $"耗时：{sw.ElapsedMilliseconds}ms"));
            }, cts.Token));
            var taskDelay = Task.Delay(Param.TimeOut);
            tasks.Add(taskDelay);
            Task.WhenAny(tasks.ToArray()).ContinueWith((x) =>
           {
               if (taskDelay.IsCompleted)
               {
                   statusStrip1.Invoke(new Action(() =>
                   {
                       ErrorStatusLabel.Text = $"测试超时({Param.TimeOut}ms)，请重试！";
                       ErrorStatusLabel.BackColor = Color.Red;
                   }));
                   cts.Cancel();
               }
               else statusStrip1.Invoke(new Action(() =>
                {
                    ErrorStatusLabel.Text = $"测试完成！";
                    ErrorStatusLabel.BackColor = Color.Green;
                }));
               this.Focus();
           });

        }
        private bool AnalysisText(string text)
        {
            if (text == PASSSTRING)//|No device!
                return true;
            else
                return false;
        }
        private void DrawTextOnPanel(Panel pl, bool r)
        {
            var text = r ? "OK" : "NG";
            Color color = r ? Color.Lime : Color.Red;
            Graphics g = pl.CreateGraphics();
            Font drawFont = new Font("微软雅黑", 40, FontStyle.Bold);
            SolidBrush drawBrush = new SolidBrush(Color.Black);
            SizeF sz = g.MeasureString(text, drawFont);
            var location = new PointF(pl.ClientRectangle.Width / 2 - sz.Width / 2, pl.ClientRectangle.Height / 2 - sz.Height / 2 + 4);
            SolidBrush s = new SolidBrush(color);
            g.FillRectangle(s, pl.Width / 2 - 70, pl.Height / 2 - 50, 140, 100);
            g.DrawString(text, drawFont, drawBrush, location);
            g.Dispose();
            pl.SuspendLayout();
        }
        private string GetResultText()
        {
            if (string.IsNullOrEmpty(ResultIntptrLabe.Text))
            {
                MessageBox.Show("未找到结果控件的句柄！");
                return null;
            }
            var resultIntptr = (IntPtr)(Convert.ToInt32(ResultIntptrLabe.Text));
            if (resultIntptr == IntPtr.Zero)
                return null;
            int length = WinApi.GetWindowTextLength(resultIntptr);
            StringBuilder windowName = new StringBuilder(length + 8);
            WinApi.GetWindowText(resultIntptr, windowName, windowName.Capacity);
            return windowName.ToString();
        }
        private void SaveBtn_Click(object sender, EventArgs e)
        {
            SaveParam();
        }

        private void playSelectedItemToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (CurrentMacro.Count < 1)
                return;
            Clipboard.SetDataObject(BarcodeTx.Text);
            var temp = lvEvents.SelectedItems.Cast<ListViewItem>().ToList().Select(x => x.Tag).Cast<IMacroEvent>().ToList();
            using (formMacroPlaying mp = new formMacroPlaying(temp.ToArray()))
            {
                this.Hide();
                mp.ShowDialog();
                this.Show();
            }
        }

        private void NewTsmitem_Click(object sender, EventArgs e)
        {
            Recorder.MouseMovementCaptureDelay = 100;
            Recorder.CaptureMouseMovements = true;
            if (fm != null)
                fm.Close();
            fm = new Frm_Main(new Point(1, 1));
            fm.Show();
            if (mn != null)
                mn.Close();
            mn = new formMacroNotify(Recorder, false, true, 0);
            mn.OnEvent += Mn_OnEvent;
            _editFlag = 1;
            ClearCurrent();
            this.Hide();
            mn.TopMost = true;
            mn.Show();
        }

        private void Mn_OnEvent()
        {
            fm.Close();
            fm = null;
            mn.Close();
            mn = null;
            this.Show();
        }

        private void PlayTsmitem_Click(object sender, EventArgs e)
        {
            if (ResultEvents.Count < 1)
                return;
            PlayTsmitem.BackColor = selectedToolStripMenuItem.BackColor;
            fm = new Frm_Main(new Point(1, 1));
            fm.Show();
            mp = new formMacroPlaying(ResultEvents.ToArray());
            mp.OnEvent += Mp_OnEvent;
            this.Hide();
            mp.Show();

        }

        private void Mp_OnEvent()
        {
            Show();
            mp.Close();
            ResultIntptrLabe.Text = fm.FormHandle.ToString();
            ResultIntptrLabe.Focus();
            ResultIntptrLabe.Select(0, 0);
            fm.Close();
            fm = null;
        }

        private void RemoveTsmitem_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                foreach (ListViewItem i in listView1.SelectedItems)
                {
                    // ListViewItem i = lvEvents.SelectedItems[0];
                    IMacroEvent mEvent = (IMacroEvent)i.Tag;
                    ResultEvents.Remove(mEvent);
                    Recorder.Remove(mEvent);
                    listView1.Items.Remove(i);
                }
            }
        }

        private void ExtractTsmitem_Click(object sender, EventArgs e)
        {
            var result1 = false;
            var result2 = false;
            var result = false;
            ResultTextLabel.Text = "";
            StatusLabel.Text = "";
            TextLable.Text = "";
            ColorLabel.Text = "";
            ColorLabel.BackColor = Color.Gray;
            RunStatusEnum status = RunStatusEnum.Default;
            if (TextRbtn.Checked || BothRbtn.Checked)//文本提取
            {
                var text = GetResultText();
                TextLable.Text = text;
                if (!string.IsNullOrEmpty(text))
                {
                    status = GetStatusByText(text);
                    StatusLabel.Text = status.ToString();
                    if (status == RunStatusEnum.Finished)
                        result1 = text == PASSSTRING;
                }
            }
            if (ColorRbtn.Checked || BothRbtn.Checked)//颜色提取
            {
                IntPtr hdc = WinApi.GetDC(new IntPtr(0));//取到设备场景(0就是全屏的设备场景)
                uint c = WinApi.GetPixel(hdc, Param.ColorX, Param.ColorY);
                int r = (int)(c & 0xFF);
                int g = (int)(c & 0xFF00) / 256;
                int b = (int)(c & 0xFF0000) / 65536;
                ColorLabel.Text = $"r:{r},g:{g},b:{b}";
                ColorLabel.BackColor = Color.FromArgb(r, g, b);
                status = GetStatusByColor(r, g, b);
                StatusLabel.Text = status.ToString();
                if (status == RunStatusEnum.Finished)
                {
                    result2 = GetResultByColor(r, g, b) == 2;
                }
            }
            if (status == RunStatusEnum.Finished)
            {
                if (BothRbtn.Checked) result = result1 && result2;
                else if (TextRbtn.Checked) result = result1;
                else result = result2;
                ResultTextLabel.Text = result ? "OK" : "NG";
            }

        }
        private RunStatusEnum GetStatusByText(string text)
        {
            if (Param.RuningTexts.Contains(text))
                return RunStatusEnum.Running;
            else
                return RunStatusEnum.Finished;
        }
        private RunStatusEnum GetStatusByColor(int r, int g, int b)
        {
            if (r > 200 && g > 200 && b < 10)
                return RunStatusEnum.Running;
            else
                return RunStatusEnum.Finished;
        }
        private int GetResultByColor(int r, int g, int b)
        {
            if (r > 200 && g < 10 && b < 10)
                return 1;//NG
            else if (r < 10 && g > 200 && b < 10)
                return 2;//OK
            else return 3;
        }
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                Frm_Main mp = new Frm_Main();
                Hide();
                if (mp.ShowDialog() == DialogResult.OK)
                {
                    var name = mp.FormClassName;
                    if (name.EndsWith(" (unicode)"))
                        name = name.Replace(" (unicode)", "");
                    MainHandleTx.Text = mp.FormHandle.ToString();
                    ClassTextTx.Text = name;
                    TitleTextTx.Text = mp.FormTitle;
                }
                Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void MoveFormBtn_Click(object sender, EventArgs e)
        {
            WinApi.SetWindowPos((IntPtr)(Convert.ToInt32(MainHandleTx.Text)), 0, 0, 0, 0, 0, 0x0005);
            WinApi.SetForegroundWindow((IntPtr)(Convert.ToInt32(MainHandleTx.Text)));
        }

        private void FindMainHandleBtn_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(TitleTextTx.Text) || string.IsNullOrEmpty(ClassTextTx.Text))
                MessageBox.Show("请先使用小工具查找目标窗体信息");
            MainHandleTx.Text = WinApi.FindWindow(ClassTextTx.Text, TitleTextTx.Text).ToString();
        }

        private void SetColorLocationTsmitem_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count != 1)
            {
                MessageBox.Show("请先选择一项包含坐标的行");
                return;
            }
            IMacroEvent mEvent = (IMacroEvent)listView1.SelectedItems[0].Tag;
            if (mEvent is MacroEvent_Mouse mouse)
            {
                ColorXLabel.Text = mouse.Event.Location.X.ToString();
                ColorYLabel.Text = mouse.Event.Location.Y.ToString();
                Param.ColorX = mouse.Event.Location.X;
                Param.ColorY = mouse.Event.Location.Y;
            }
            else
            {
                MessageBox.Show("请先选择一项包含坐标的行");
                return;
            }
        }

        private void PlaySelectedItemsTsmitem_Click(object sender, EventArgs e)
        {
            if (ResultEvents.Count < 1)
                return;
            var temp = listView1.SelectedItems.Cast<ListViewItem>().ToList().Select(x => x.Tag).Cast<IMacroEvent>().ToList();
            using (formMacroPlaying mp = new formMacroPlaying(temp.ToArray()))
            {
                this.Hide();
                mp.ShowDialog();
                this.Show();
            }
        }

        private void NextStepBtn_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 2;
            PlayTsmitem.BackColor = Color.Yellow;
            cmFindResultHandle.Show(listView1, listView1.PointToClient(Cursor.Position));
        }

        private void InitBtn_Click(object sender, EventArgs e)
        {
            int index = 0;
            try
            {
                FindMainHandleBtn_Click(null, null); index = 1;
                MoveFormBtn_Click(null, null); index = 2;
                NextStepBtn_Click(null, null); index = 3;
                if (Param.ExtractType == ExtractEnum.Text || Param.ExtractType == ExtractEnum.Both)
                {
                    PlayTsmitem_Click(null, null); index = 4;
                }
                tabControl1.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化出错，错误代码{index}，异常{ex.Message}");
            }
        }
    }
}
